package com.tzinfo.tzb;

import java.io.File;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.galhttprequest.GalHttpRequest;
import com.galhttprequest.GalHttpRequest.GalHttpLoadTextCallBack;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.tzinfo.data.TztData;
import com.tzinfo.tzb.domain.DefaultResult;
import com.tzinfo.tzb.domain.DiaryList;
import com.tzinfo.tzb.domain.DiaryList.DiaryData;
import com.tzinfo.tzb.domain.DiaryList.DiaryData.DiaryPhoto;
import com.tzinfo.tzb.util.FileConfig;
import com.tzinfo.tzb.util.HttpTools;
import com.tzinfo.tzb.util.TzbCommonData;
import com.tzinfo.tzt.R;
import com.yxw.util.OutLog;
import com.yxw.view.util.ResFinder;

public class TzbMyDirayWriteActivity extends TzbBaseActivity {

	public static TzbMyDirayWriteActivity activity;
	// 标志
	private boolean isPub = true;
	private int flag = 0;
	private boolean isNeedReflash = false;
	private boolean isChanged = false;

	// 参数

	// UI组件
	private Button bt_topbar_r1, bt_diray_delete;
	private ImageView img_riji, img_delete, img_touxiang;
	private TextView text_diary_title;
	private TextView text_diary_context;
	private TextView text_title;
	private AlertDialog dlg;
	// 数据
	private Object imagePath = null;
	DefaultResult result = null;
	public DiaryData diaryData = null;
	private DiaryList diaryList;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(ResFinder.getR(this,
				"R.layout.tzb_ac_main_my_write_diray"));
		activity = this;
		initParameter();
		init();
	}

	private void initParameter() {
		Intent thisIntent = this.getIntent();
		isPub = thisIntent.getBooleanExtra("isPub", true);
		flag = thisIntent.getIntExtra("flag", 0);
		OutLog.LogE("yxw", flag + "");
		switch (flag) {
		case 1:
			diaryList = TzbDirayListActivity.diaryList;
			break;
		default:
			diaryList = TzbCommonData.diaryList;
			break;
		}
		if(diaryList!=null&&diaryList.getData().size()>TzbCommonData.diaryItem){
			diaryData = diaryList.getData().get(TzbCommonData.diaryItem);
		}
	}

	private void init() {
		// 加载滚动进入条
		mProgressBar = (ProgressBar) ResFinder.findViewById(this,
				"R.id.progressbar_loding");
		img_riji = (ImageView) ResFinder.findViewById(this, "R.id.img_riji");
		img_delete = (ImageView) ResFinder
				.findViewById(this, "R.id.img_delete");
		img_touxiang = (ImageView) ResFinder.findViewById(this,
				"R.id.img_touxiang");
		text_diary_title = (TextView) ResFinder.findViewById(this,
				"R.id.text_diary_title");
		text_diary_context = (TextView) ResFinder.findViewById(this,
				"R.id.text_diary_context");
		text_title = (TextView) ResFinder.findViewById(this, "R.id.text_title");
		bt_topbar_r1 = (Button) ResFinder.findViewById(this,
				"R.id.bt_topbar_r1");
		bt_diray_delete = (Button) ResFinder.findViewById(this,
				"R.id.bt_diray_delete");
		if (!isPub) {
			bt_topbar_r1.setText("修改");
			text_title.setText("编辑");
			bt_diray_delete.setVisibility(View.VISIBLE);
			if (diaryData != null) {
				text_diary_title.setText(diaryData.getTitle());
				text_diary_context.setText(diaryData.getMessage());
				if (diaryData.getPhoto() != null
						&& diaryData.getPhoto().size() > 0) {
					imagePath = diaryData.getPhoto().get(0);
					imageLoader.displayImage(diaryData.getPhoto().get(0)
							.getPicfile(), img_riji, options);
					img_delete.setVisibility(View.VISIBLE);
				}
			}
		}
		if(TzbCommonData.userInfoModel!=null){
			imageLoader.displayImage(TzbCommonData.userInfoModel
					.getData().getAvatar(), img_touxiang, options);
		}
	}

	public void fabiaoDiray(View v) {
		// showProgressBar();
		dialog.show();
		String url = "";
		if (isPub) {
			url = ResFinder.getResString(this, "R.string.tzb_url_DiaryAdd")
					+ "?sessionid=" + TztData.userInfo.getData().getSessionID()
					+ "&title=" + text_diary_title.getText().toString()
					+ "&message=" + text_diary_context.getText().toString();
		} else {
			url = ResFinder.getResString(this, "R.string.tzb_url_DiaryUpdate")
					+ "?sessionid=" + TztData.userInfo.getData().getSessionID()
					+ "&title=" + text_diary_title.getText().toString()
					+ "&message=" + text_diary_context.getText().toString()
					+ "&diaryid=" + diaryData.getId();
		}
		OutLog.LogE("yxw", url);
		GalHttpRequest galHttpRequest = new GalHttpRequest(this);
		galHttpRequest.setCacheEnable(false);
		galHttpRequest.setURL(url);
		galHttpRequest.startAsynRequestString(new GalHttpLoadTextCallBack() {

			@Override
			public void textLoaded(String arg0) {
				OutLog.LogE("yxw", "json:" + arg0);
				Gson gson = new Gson();
				java.lang.reflect.Type type = new TypeToken<DefaultResult>() {
				}.getType();
				result = gson.fromJson(arg0, type);
				OutLog.LogE("yxw", "result:" + result.toString());
				if (result.isSuccess()) {
					isChanged = true;
					if (isPub) {
						Toast.makeText(TzbMyDirayWriteActivity.this,
								"恭喜你，日志发表成功！", Toast.LENGTH_SHORT).show();
						isNeedReflash = true;
					} else {
						Toast.makeText(TzbMyDirayWriteActivity.this,
								"恭喜你，日志修改成功！", Toast.LENGTH_SHORT).show();
						diaryData.setTitle(text_diary_title.getText() + "");
						diaryData.setMessage(text_diary_context.getText() + "");
						diaryList.getData().remove(TzbCommonData.diaryItem);
						diaryList.getData().add(TzbCommonData.diaryItem,
								diaryData);
					}
					if (imagePath instanceof String) {
						new Thread(upLoadImageRun).start();
					} else {
						goback(null);
						dialog.dismiss();
					}

				} else {
					Toast.makeText(TzbMyDirayWriteActivity.this,
							"抱歉，日志发表失败，请重试！", Toast.LENGTH_SHORT).show();
					dialog.dismiss();
				}

			}
		});

	}

	public void deleteDiary(View v) {

		new AlertDialog.Builder(this).setCancelable(false)
				.setMessage("您确定要删除该日志吗？")
				.setPositiveButton("确定", new DialogInterface.OnClickListener()

				{
					public void onClick

					(DialogInterface dialog, int which) {
						requestDeleteDiary();
					}
				})
				.setNegativeButton("取消", new DialogInterface.OnClickListener()

				{
					public void onClick(

					DialogInterface dialogInterface, int

					whichButton) {
					}
				}).show();

	}

	private void requestDeleteDiary() {
		dialog.show();
		String url = "";
		url = ResFinder.getResString(this, "R.string.tzb_url_DiaryDelete")
				+ "?sessionid=" + TztData.userInfo.getData().getSessionID()
				+ "&diaryid=" + diaryData.getId();
		OutLog.LogE("yxw", url);
		GalHttpRequest galHttpRequest = new GalHttpRequest(this);
		galHttpRequest.setCacheEnable(false);
		galHttpRequest.setURL(url);
		galHttpRequest.startAsynRequestString(new GalHttpLoadTextCallBack() {

			@Override
			public void textLoaded(String arg0) {
				OutLog.LogE("yxw", "json:" + arg0);
				Gson gson = new Gson();
				java.lang.reflect.Type type = new TypeToken<DefaultResult>() {
				}.getType();
				result = gson.fromJson(arg0, type);
				OutLog.LogE("yxw", "result:" + result.toString());
				dialog.dismiss();
				if (result.isSuccess()) {
					Toast.makeText(TzbMyDirayWriteActivity.this, "恭喜你，日志删除成功！",
                            Toast.LENGTH_SHORT).show();
					diaryList.getData().remove(TzbCommonData.diaryItem);
					isNeedReflash = true;
					Intent intent = new Intent();
					intent.putExtra(TzbCommonData.IS_OK, true);
					intent.putExtra(TzbCommonData.IS_NEED_REFLASH,
							isNeedReflash);
					intent.putExtra(TzbCommonData.IS_DELETE, true);
					TzbMyDirayWriteActivity.this.setResult(1, intent);
					TzbMyDirayWriteActivity.this.finish();
				} else {
					Toast.makeText(TzbMyDirayWriteActivity.this,
							"抱歉，日志删除失败，请重试！", Toast.LENGTH_SHORT).show();
				}
			}
		});
	}

	@Override
	public void goback(View view) {
		Intent intent = new Intent();
		intent.putExtra(TzbCommonData.IS_OK, isChanged);
		intent.putExtra(TzbCommonData.IS_NEED_REFLASH, isNeedReflash);
		TzbMyDirayWriteActivity.this.setResult(1, intent);
		super.goback(view);
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			goback(null);
			return false;
		} else {
			return super.onKeyDown(keyCode, event);
		}
	}

	// 显示选择相册or照片
	public void showAddImageDialog(View v) {
		if (!(imagePath instanceof DiaryPhoto)) {
			final CharSequence[] items = { "相册", "拍照", "取消" };

			dlg = new AlertDialog.Builder(this).setTitle("选择照片")
					.setItems(items, new DialogInterface.OnClickListener() {

						@Override
						public void onClick(DialogInterface dialog, int which) {
							// TODO Auto-generated method stub
							// 这里item是根据选择的方式，
							// 在items数组里面定义了两种方式，拍照的下标为1所以就调用拍照方法
							if (which == 0) {
								Intent getImage = new Intent(
										Intent.ACTION_GET_CONTENT);
								getImage.addCategory(Intent.CATEGORY_OPENABLE);
								getImage.setType("image/jpeg");
								startActivityForResult(getImage, 2);
							} else if (which == 1) {
								Intent getImageByCamera = new Intent(
										"android.media.action.IMAGE_CAPTURE");
								File tempFile = new File(FileConfig.IMAGE_PATH);
								if (!tempFile.isDirectory()) {
									tempFile.mkdirs();
								}
								FileConfig.IMAGE_NAME = FileConfig
										.getRandomJpgName();
								Uri imageUri = Uri.fromFile(new File(
										FileConfig.IMAGE_PATH,
										FileConfig.IMAGE_NAME));
								// 指定照片保存路径（SD卡），image.jpg为一个临时文件，每次拍照后这个图片都会被替换
								getImageByCamera.putExtra(
										MediaStore.EXTRA_OUTPUT, imageUri);
								startActivityForResult(getImageByCamera, 3);
							} else {
								dlg.dismiss();
							}
						}
					}).create();
			dlg.show();
		}
	}

	public void onDeleteImage(View v) {
		new AlertDialog.Builder(TzbMyDirayWriteActivity.this)
				.setTitle("友情提醒")
				.setMessage("您确定要删除这张照片吗？")
				.setPositiveButton("确	定",
						new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog,
									int which) {
								deleteImage(imagePath);
							}
						})
				.setNegativeButton("取	消",
						new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog,
									int which) {
							}
						}).show();
	}

	private void deleteImage(Object object) {
		if (object instanceof String) {
			dialog.show();
			img_riji.setImageResource(R.drawable.tzb_image_add);
			img_delete.setVisibility(View.GONE);
			imagePath = null;
			Toast.makeText(TzbMyDirayWriteActivity.this, "已删除图片！", Toast.LENGTH_LONG).show();
			dialog.dismiss();
		} else {// 网络的删除需要通过HTTP请求
			dialog.show();
			DiaryPhoto diaryPhoto = (DiaryPhoto) object;
			GalHttpRequest galHttpRequest = new GalHttpRequest(
					TzbMyDirayWriteActivity.this);
			String url = ResFinder.getResString(this,
					"R.string.tzb_url_DiaryPhotoDelete")
					+ "?sessionid="
					+ TztData.userInfo.getData().getSessionID()
					+ "&diaryid="
					+ diaryData.getId() + "&photoid=" + diaryPhoto.getId();
			OutLog.LogE("yxw", "delete:" + url);
			galHttpRequest.setCacheEnable(false);
			galHttpRequest.setURL(url);
			galHttpRequest
					.startAsynRequestString(new GalHttpLoadTextCallBack() {

						@Override
						public void textLoaded(String arg0) {
							DefaultResult result = null;
							Gson gson = new Gson();
							java.lang.reflect.Type type = new TypeToken<DefaultResult>() {
							}.getType();
							result = gson.fromJson(arg0, type);
							OutLog.LogE("yxw", "result:" + result.toString());
							if (result.isSuccess()) {
								img_riji.setImageResource(R.drawable.tzb_image_add);
								img_delete.setVisibility(View.GONE);
								imagePath = null;
								Toast.makeText(TzbMyDirayWriteActivity.this,
										"已删除图片！", Toast.LENGTH_SHORT).show();
								isChanged = true;
								isNeedReflash = true;
							} else {
								Toast.makeText(TzbMyDirayWriteActivity.this,
										result.getMsg(), Toast.LENGTH_SHORT).show();
							}
							dialog.dismiss();
						}
					});
		}

	}

	Runnable upLoadImageRun = new Runnable() {

		@Override
		public void run() {
			Message message = handler.obtainMessage();
			String url = ResFinder.getResString(TzbMyDirayWriteActivity.this,
					"R.string.tzb_url_DiaryPhotoAdd")
					+ "?sessionid="
					+ TztData.userInfo.getData().getSessionID()
					+ "&diaryid="
					+ diaryData.getId();
			OutLog.LogE("yxw", "add:" + url);
			String path = (String) imagePath;
			if (path != null) {
				String jsonString = HttpTools.uploadImage(url, path);
				Log.e("jsonImage", jsonString);
				DefaultResult result = null;
				Gson gson = new Gson();
				java.lang.reflect.Type type = new TypeToken<DefaultResult>() {
				}.getType();
				result = gson.fromJson(jsonString, type);
				if (result.isSuccess()) {
					message.arg1 = 1;
				} else {
					message.arg1 = -1;
				}
			}
			handler.sendMessage(message);
		}
	};
	Handler handler = new Handler() {
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			switch (msg.arg1) {
			case 1:
				dialog.dismiss();
				isNeedReflash = true;
				isChanged = true;
				goback(null);
				break;
			case -1:
				dialog.dismiss();
				isChanged = true;
				Toast.makeText(TzbMyDirayWriteActivity.this, "图片上传失败！",
						Toast.LENGTH_SHORT).show();
				goback(null);
				break;
			}
		}
	};

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		BitmapFactory.Options option = null;
		switch (requestCode) {
		case 2:
			if (data != null) {
				img_delete.setVisibility(View.VISIBLE);
				Uri selectedImage = data.getData();
				String[] filePathColumn = { MediaStore.Images.Media.DATA };

				Cursor cursor = getContentResolver().query(selectedImage,
						filePathColumn, null, null, null);
				cursor.moveToFirst();
				int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
				String picturePath = cursor.getString(columnIndex);
				cursor.close();
				// 图片的压缩显示，如果不压缩，当图片太大时会导致内存溢出 或者应用很卡
				option = new BitmapFactory.Options();
				option.inSampleSize = 5;
				imagePath = picturePath;
				img_riji.setImageBitmap(BitmapFactory.decodeFile(picturePath,
						option));
			}
			break;
		case 3:
			img_delete.setVisibility(View.VISIBLE);
			// 图片的压缩显示，如果不压缩，当图片太大时会导致内存溢出 或者应用很卡
			option = new BitmapFactory.Options();
			String path = FileConfig.IMAGE_PATH + "/" + FileConfig.IMAGE_NAME;
			option.inSampleSize = 5;
			imagePath = path;
			img_riji.setImageBitmap(BitmapFactory.decodeFile(path, option));
			break;
		}
		super.onActivityResult(requestCode, resultCode, data);
	}
}
